let BosClient = require('bce-sdk-js').BosClient;
let Promise = require('promise');
let Consts = require('../consts.js');
// let Content = require('../models/Content');

var bceHelper = {
	initBosClient: function(cb) {
		const config = {
			endpoint: Consts.BCE.ENDPOINT, //传入Bucket所在区域域名
			credentials: {
				ak: Consts.BCE.AK, //您的AccessKey
				sk: Consts.BCE.SK //您的SecretAccessKey
			}
		};

		var client = new BosClient(config);

		cb && cb(client);
	},

	putObjectFromFile: function(client, bucket, key, pathname, cb) {
		return new Promise(function (resolve, reject) {
			client.putObjectFromFile(bucket, key, pathname)
			    .then(function(response) {
			    	resolve(response);
			    })
			    .catch(function(error) {
			    	reject(error);
			    });
		})
	},

	getBceUrl: function(filename, bucket) {
		return Consts.BCE.ENDPOINT.replace('://','://' + bucket + '.') + '/' + filename;
	},

	deleteObject: function(bucket, key) {
		this.initBosClient(function(client) {
			client.deleteObject(bucket, key);
		})
	},

	listObjects: function(bucket, maker) {
		return new Promise(function (resolve, reject) {
			var options = {
			    delimiter: '/',
			    marker: maker
			};
			bceHelper.initBosClient(function(client) {
				client.listObjects(bucket, options)
				    .then(function (response) {
				    	var isTruncated = response.body.isTruncated;
				        var contents = response.body.contents;
				        resolve(contents, isTruncated);
				    })
				    .catch(function (error) {
				    	reject(error, false);
				        // 查询失败
				    });
			})
		})
	},

	putObject: function(client, bucket, object, buffer) {
		return new Promise(function (resolve, reject) {
			client.putObject(bucket, object, buffer)
			  .then(function(response) {
			  		resolve(response);
			  })
			  .catch(function(response) {
			  		reject(response);
			  });
		})
	}
}

function getContents(category) {
    return new Promise(function(resove, reject) {
        Content.find({
            category: category
        }, function(err, contents) {
            if (err) {
                reject(err);
                return res.send(resultJson(2));
            }
            resove(contents);
        })
    })
}

// bceHelper.listObjects('sabine-video',0)
// 	.then(function(videos, isTruncated) {
// 		getContents(1).
// 		return {
// 			bceVideos: videos,
// 			isTruncated: isTruncated,
// 			dbVideos: getContents(1)
// 		}
// 	})
// 	.then(function(results) {
// 		console.log('results',results);
// 	})

module.exports = bceHelper;